#include <event2/event.h>
#include <event2/thread.h>
#include <functional>
#include <queue>
#include <mutex>
#include <atomic>
#include <iostream>

class LibEventDispatcher
{
private:
    struct event_base* base_;
    struct event* task_event_;
    std::queue<std::function<void()>> task_queue_;
    std::mutex queue_mutex_;
    std::atomic<bool> shutdown_{false};

public:
    LibEventDispatcher() : base_(nullptr), task_event_(nullptr) {
        // 初始化libevent线程支持
        evthread_use_pthreads();
        
        // 创建事件基础
        base_ = event_base_new();
        if (!base_) {
            throw std::runtime_error("Failed to create event base");
        }
        
        // 创建用于处理任务的事件
        task_event_ = event_new(base_, -1, 0, task_event_callback, this);
        if (!task_event_) {
            event_base_free(base_);
            throw std::runtime_error("Failed to create task event");
        }
    }
    
    ~LibEventDispatcher() {
        if (task_event_) {
            event_free(task_event_);
        }
        if (base_) {
            event_base_free(base_);
        }
    }
    
    // 禁止拷贝
    LibEventDispatcher(const LibEventDispatcher&) = delete;
    LibEventDispatcher& operator=(const LibEventDispatcher&) = delete;

    // 从其他线程派发任务到事件循环线程
    void dispatch(std::function<void()> func) {
        {
            std::lock_guard<std::mutex> lock(queue_mutex_);
            task_queue_.push(std::move(func));
        }
        
        // 通知事件循环有新任务
        event_active(task_event_, 0, 0);
    }
    
    // 在事件循环线程中运行
    void run() {
        if (base_) {
            event_base_dispatch(base_);
        }
    }
    
    // 阻塞运行事件循环
    void run_blocking() {
        while (!shutdown_) {
            event_base_loop(base_, EVLOOP_ONCE);
        }
    }
    
    // 运行单次事件循环迭代
    void run_once() {
        event_base_loop(base_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
    }
    
    // 停止事件循环
    void stop() {
        shutdown_ = true;
        if (base_) {
            event_base_loopbreak(base_);
        }
    }

private:
    // 静态回调函数，libevent要求回调函数是静态的
    static void task_event_callback(evutil_socket_t fd, short events, void* arg) {
        LibEventDispatcher* dispatcher = static_cast<LibEventDispatcher*>(arg);
        dispatcher->process_tasks();
    }
    
    // 处理任务队列
    void process_tasks() {
        std::queue<std::function<void()>> local_queue;
        
        // 快速交换队列以最小化锁持有时间
        {
            std::lock_guard<std::mutex> lock(queue_mutex_);
            local_queue.swap(task_queue_);
        }
        
        // 在无锁状态下执行所有任务
        while (!local_queue.empty()) {
            auto task = std::move(local_queue.front());
            local_queue.pop();
            if (task) {
                try {
                    task();
                } catch (const std::exception& e) {
                    std::cerr << "Exception in dispatched task: " << e.what() << std::endl;
                } catch (...) {
                    std::cerr << "Unknown exception in dispatched task" << std::endl;
                }
            }
        }
    }
};

#include <iostream>
#include <thread>
#include <chrono>

int main() {
    LibEventDispatcher dispatcher;
    
    // 启动工作线程
    std::thread worker([&dispatcher]() {
        for (int i = 0; i < 5; ++i) {
            dispatcher.dispatch([i]() {
                std::cout << "Task " << i << " executed in event loop thread" << std::endl;
            });
            
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
        
        // 发送停止信号
        dispatcher.dispatch([&dispatcher]() {
            std::cout << "Stopping event loop" << std::endl;
            dispatcher.stop();
        });
    });
    
    // 在主线程中运行事件循环
    std::cout << "Starting event loop..." << std::endl;
    dispatcher.run();
    
    worker.join();
    std::cout << "Program finished" << std::endl;
    
    return 0;
}